$(document).ready(function() {
	$('.map').click(mapMove);
});

function getMouseXY(event, element) {
	return {x: event.pageX - element.offsetLeft, y: event.pageY - element.offsetTop};
}

function getDirection(arrayMouseXY) {
	return {x: arrayMouseXY['x'] - 400, y: 300 - arrayMouseXY['y']};
}

function getBackgroundPositionArray(element) {
	arrayPositionString = element.css("background-position").replace(/px/g, "").split(" ");
	return {x: Number(arrayPositionString[0]), y: Number(arrayPositionString[1])};
}

function checkCollision() {
}

function mapMove(event) {
	var arrayMouseXY = getMouseXY(event, this);
	var arrayDirection = getDirection(arrayMouseXY);
	mapMove1(arrayDirection);
}

function mapMove1(arrayDirection) {
	var yourSprite = $(".you");

	$(".sprite").each(function(index) {
		arrayBackgroundPosition = getBackgroundPositionArray($(this));

		$(this).animate({backgroundPosition : (arrayBackgroundPosition['x'] - arrayDirection['x']) + "px "
				+ (arrayBackgroundPosition['y'] + arrayDirection['y']) + "px"}, {
			complete: function() {/*
				if (yourSprite.position().left + yourSprite.width() > $(this).position().left
						&& yourSprite.position().left < $(this).position().left + $(this).width()
						&& yourSprite.position().top + yourSprite.height() > $(this).position().top
						&& yourSprite.position().top < $(this).position().top + $(this).height()) {
					alert("en rango");
				}
		
				if ($(this).position().left < 0) {
					//$(this).css("left", "0px");
				}
		
				if ($(this).position().left < 0 || $(this).position().left + $(this).width() > 800
						|| $(this).position().top < 0 || $(this).position().top + $(this).height() > 600) {
					//$(this).hide();
				}
				else {
					$(this).show();
					if ($(this).position().left < 0 || $(this).position().left + $(this).width() > 800
							|| $(this).position().top < 0 || $(this).position().top + $(this).height() > 600) {
						//$(this).hide();
					}
				}
			*/},
		
			step: function(now, fx) {
				arrayBackgroundPosition = getBackgroundPositionArray(yourSprite);

				yourSprite.css("background-position", (arrayBackgroundPosition['x'] + 48) + "px " + "0")
			},
			duration: 300
		});
	});
}
